package com.spring.security.config;

import com.spring.security.service.MyUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @Classname: UserSecurityConfig
 * @Description: 查询数据库, 获取登录人信息
 * @Date: 2021/12/27
 * @Author: HuWei
 */
@Configuration
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailServiceImpl myUserDetailService;

    @Autowired
    private DataSource dataSource;

    /**
     * 查询数据库获取登录人信息
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailService).passwordEncoder(passwordEncoder());
    }

    /**
     * 配置自动登录数据源
     */
    @Bean
    public PersistentTokenRepository tokenRepository(){
        // 获得对象
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        // 在对象中放入我们定义的数据源
        jdbcTokenRepository.setDataSource(dataSource);
        // 自动创建自动登录需要的表
        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

    /**
     * 设置自定义登录页面和设置不需要验证就能登录的路径
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 定义退出
        http.logout()
                // 设置退出路径,不需要写逻辑,Security会自动帮我们实现
                .logoutUrl("/loginout")
                // 退出后访问的路径
                .logoutSuccessUrl("/security/loginOut").permitAll();
        // 自定义403页面
        http.exceptionHandling().accessDeniedPage("/unAuth.html");
        http.formLogin()
                // 设置自定义的登录页面路径
                .loginPage("/login.html")
                // 设置登录访问的路径,不需要编写逻辑,Security会自动帮我们实现
                .loginProcessingUrl("/user/login").permitAll()
                // 登录成功后访问的路径
                .defaultSuccessUrl("/loginSuccess.html")
                // 设置不需要验证就能访问的路径
                .and().authorizeRequests().antMatchers("/","/security/unLogin","/user/login").permitAll()
                    // 设置只有admin角色可以访问的路径
                    //.antMatchers("/security/roleAdmin").hasAuthority("admins")
                    // 设置admin和role角色都可以访问
                    //.antMatchers("/security/roleAdmin").hasAnyAuthority("admins","manager")
                    // 设置sale可以访问
                    // .antMatchers("/security/roleAdmin").hasRole("sale")
                    // 设置sale和test都可以访问
                    //.antMatchers("/security/roleAdmin").hasAnyRole("test","sale")
                    .anyRequest().authenticated()
                // 设置自动登录
                .and().rememberMe()
                // 获取自动登录数据源
                .tokenRepository(tokenRepository())
                // 自动登录保存时间
                .tokenValiditySeconds(30)
                // 自动登录调用的登录服务
                .userDetailsService(myUserDetailService)
                // 关闭csrf防护
                .and().csrf().disable();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}